package com.spice.im.jspeex.voice;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xiph.speex.AudioFileWriter;
import org.xiph.speex.OggSpeexWriter;
import org.xiph.speex.SpeexEncoder;
public class JSEncode {
	public static final int SAMPLE_RATE = 16000;
	public static final int CHANNELS = 1;
	public static final int SPEEX_MODE = 0;
	public static final int SPEEX_QUALITY = 8;
	private SpeexEncoder mEncoder;
	public void initEncoder() {
		mEncoder = new SpeexEncoder();
		mEncoder.init(SPEEX_MODE, SPEEX_QUALITY, SAMPLE_RATE, CHANNELS);
	}
	public void encodeFile(final File inputFile, final File outputFile) throws IOException {
		DataInputStream input = null;
		AudioFileWriter output = null;
		try {
			input = new DataInputStream(new FileInputStream(inputFile));
			output = new OggSpeexWriter(SPEEX_MODE, SAMPLE_RATE, CHANNELS, 1, false);
			output.open(outputFile);
			output.writeHeader("Encoded with: " + SpeexEncoder.VERSION);

			byte[] buffer = new byte[2560]; // 2560 is the maximum needed value (stereo UWB)
			int packetSize = 2 * CHANNELS * mEncoder.getFrameSize();

			while (true) {
				input.readFully(buffer, 0, packetSize);
				mEncoder.processData(buffer, 0, packetSize);
				int encodedBytes = mEncoder.getProcessedData(buffer, 0);
				if (encodedBytes > 0) {
					output.writePacket(buffer, 0, encodedBytes);
				}
			}
		} catch (EOFException e) {
			// This exception just provides exit from the loop
		} finally {
			try {
				if (input != null) {
					input.close();
				}
			} finally {
				if (output != null) {
					output.close();
				}
			}
		}
	}
}
